#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
 //   ui->PB_SEND->setFocus();
 //   ui->PB_SEND->setShortcut(QKeySequence::InsertParagraphSeparator);
 //   ui->PB_SEND->setShortcut(Qt::Key_Enter);

}

Widget::~Widget()
{
    delete ui;
}



void Widget::on_PB_SEND_clicked()
{
    QString *msg = new QString();
    if(this->ui->RB_PLAIN->isChecked()){
        msg = new QString(ui->LE_MESSAGE->text());
        this->ui->PTE_SHOW->appendPlainText("["+ui->LE_IP->text()+"]"+ui->LE_MESSAGE->text());
    }else{
        msg = new QString(ui->LE_MESSAGE->text().toUtf8().toBase64());
        this->ui->PTE_SHOW->appendPlainText("["+ui->LE_IP->text()+"]"+ui->LE_MESSAGE->text().toUtf8().toBase64());
    }
    try{
        msg+='\n';
        client = new QTcpSocket(0);
        client ->connectToHost("127.0.0.1",20382);
        QMessageBox::information(this,"Title","Error0");
        client->write("test\n");
 //       client->write(msg->toStdString().data());
        QMessageBox::information(this,"Title","Error1");
        client->flush();

            QMessageBox::information(this,"Title","Error2");
            this->ui->PTE_SHOW->appendPlainText("["+client->peerName()+"]"+client->readBufferSize());

    }catch(...){
        QMessageBox::information(this,"Title","Error");
    }

    ui->LE_MESSAGE->setText("");

}

void Widget::on_LE_MESSAGE_returnPressed()
{
    QString *msg = new QString();
    if(this->ui->RB_PLAIN->isChecked()){
        msg = new QString(ui->LE_MESSAGE->text());
        this->ui->PTE_SHOW->appendPlainText("["+ui->LE_IP->text()+":"+ui->LE_PORT->text()+"]"+ui->LE_MESSAGE->text());
    }else{
        msg = new QString(ui->LE_MESSAGE->text().toUtf8().toBase64());
        this->ui->PTE_SHOW->appendPlainText("["+ui->LE_IP->text()+":"+ui->LE_PORT->text()+"]"+ui->LE_MESSAGE->text().toUtf8().toBase64());
    }
    try{
        client = new QTcpSocket(this);
        client ->connectToHost("127.0.0.1",20382);
        client->write(msg->toUtf8());
 //       client->flush();
        if(client->canReadLine())
            this->ui->PTE_SHOW->appendPlainText("["+client->peerName()+":"+client->peerPort()+"]"+client->readLine());

    }catch(...){
        QMessageBox::information(this,"Title","Error");
    }

    ui->LE_MESSAGE->setText("");
}
